package util

import (
	"errors"
	"fmt"

	//"fmt"
	"go-chromedp-client/structs"
	"net/url"

	"strings"

	"github.com/PuerkitoBio/goquery"
)

// 获取图片链接
func ComicUrlContent(curl string, tags_arr []string, subpage string, sublink string, url_info *url.URL, url_post string, mode string, RAW string, PLACE string) (structs.Comic, error) {
	curl = BookFullUrl(curl, url_info, url_post)
	op := &structs.Options{}
	fmt.Println(curl)
	res := &structs.Comic{}
	tt, err := Get(curl, nil, *op)
	if err != nil {
		return *res, err
	}
	//	尝试3次
	if len(tt) < 500 {
		for trynum := 0; trynum < 3; trynum++ {
			tt, err = Get(curl, nil, *op)
			if len(tt) > 500 {
				break
			}
		}
	}
	if len(tt) < 500 {

		return *res, errors.New("网络异常" + tt)

	}
	if !IsUTF8([]byte(tt)) {
		bt, _ := GbkToUTF8([]byte(tt))
		tt = string(bt)
	}

	//fmt.Println(matches)
	st := ""
	tt = strings.ReplaceAll(tt, "<br>", "\r\n")
	tt = strings.ReplaceAll(tt, "<br/>", "\r\n")
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(tt))
	if err != nil {
		return *res, err
	}

	title := ""
	content := make([]string, 0)
	for kk, tag := range tags_arr {
		tag_group := strings.Split(tag, "@")
		doc.Find(tag_group[0]).Each(
			func(i int, sel *goquery.Selection) {
				rhtml := ""
				if len(tag_group) < 2 {
					if mode == "html" {
						rhtml, _ = sel.Html()
					} else {
						rhtml = sel.Text()
					}
				} else {
					rhtml, _ = sel.Attr(tag_group[1])
				}

				rhtml = strings.ReplaceAll(rhtml, "<br>", "\r\n")
				rhtml = strings.ReplaceAll(rhtml, "<br/>", "\r\n")
				//替换p的空白
				rhtml = strings.ReplaceAll(rhtml, "　　", "\r\n")
				if kk == 0 {
					title = rhtml
				} else {
					if RAW != "" && PLACE != "" {
						rhtml = strings.Replace(rhtml, RAW, PLACE, 1)
					}
					if rhtml == "" {
						return
					}
					content = append(content, rhtml)
				}

			})
	}

	//fmt.Println("subpage", subpage, strings.Contains(tt, subpage))
	//分页兼容
	if subpage == "" && (strings.Contains(st, "本章未完") || strings.Contains(st, "本页未完") || strings.Contains(st, "本节未完") || strings.Contains(st, "下一页")) {
		if strings.Contains(st, "下一节") {
			subpage = "下一节"
		}
		if strings.Contains(st, "下一页") {
			subpage = "下一页"
		}
		if strings.Contains(st, "下一章") {
			subpage = "下一章"
		}
	}

	res.Title = title
	res.Content = content
	if subpage != "" {
		nexturl := BookNextUrl(doc, subpage, curl)
		if nexturl == "" {
			return *res, nil
		}
		//去重
		isSubpage := strings.Contains(nexturl, sublink) || strings.Contains(curl, strings.Replace(nexturl, ".html", "", 1)+"/")
		if !isSubpage && sublink != "nextall" {
			return *res, nil
		}

		nexturl = BookFullUrl(nexturl, url_info, url_post)

		fmt.Println("nexturl", nexturl)

		ress, err := ComicUrlContent(nexturl, tags_arr, subpage, sublink, url_info, url_post, mode, RAW, PLACE)
		if err == nil {
			for _, v := range ress.Content {
				content = append(content, v)
			}
		}

	}

	return *res, nil

}

// 下载单张图片
func ComicImgDown(curl string, name string) (string, error) {

	op := &structs.Options{}
	fmt.Println(curl)
	tt, err := Get(curl, nil, *op)
	if err != nil {
		return err.Error(), err
	}
	//	尝试3次
	if len(tt) < 100 {
		for trynum := 0; trynum < 3; trynum++ {
			tt, err = Get(curl, nil, *op)
			if len(tt) > 500 {
				break
			}
		}
	}
	if len(tt) < 100 {

		return tt, errors.New("图片异常")

	}
	FilePutContent(name, tt, false)
	return name, nil
}
